package com.zhuiyun.project.api.sysuser.service.impl;

import com.zhuiyun.project.api.sysuser.entiy.Power;
import com.zhuiyun.project.api.sysuser.entiy.SysUser;
import com.zhuiyun.project.api.sysuser.mapper.SysUserMapper;
import com.zhuiyun.project.api.sysuser.model.SysUserModel;
import com.zhuiyun.project.api.sysuser.service.SysUserService;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.security.customizelogin.usernamepasswordcode.UsernamePasswordCodeAuthenticationToken;
import com.zhuiyun.project.security.jwt.JWTConfig;
import com.zhuiyun.project.security.jwt.JWTUtils;
import com.zhuiyun.project.util.*;
import com.zhuiyun.project.util.pageUtil.MybatisPageHelper;
import com.zhuiyun.project.util.pageUtil.PageRequest;
import com.zhuiyun.project.util.pageUtil.PageResult;
import com.zhuiyun.project.util.validator.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName SysUserServiceImpl
 * @Description 用户管理服务类 用于实现用户的增删改查 登录 注销
 * @Author zcy
 * @Date 2023/3/24 16:15
 **/
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 通过登录名获取用户信息
     *
     * @param loginName
     * @return
     */
    @Override
    public SysUser getUserByLoginName(String loginName) {
        // 判断用户登录名是否为空
        if (ObjectUtils.isNotEmpty(loginName)) {
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("loginName", loginName);
            return sysUserMapper.selectOneByExample(example);
        } else {
            return null;
        }
    }

    /**
     * 通过邮箱查询用户
     *
     * @param emailAccount
     * @return
     */
    @Override
    public SysUser getUserByEmailAccount(String emailAccount) {
        // 判断用户登录名是否为空
        if (ObjectUtils.isNotEmpty(emailAccount)) {
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("email", emailAccount);
            return sysUserMapper.selectOneByExample(example);
        } else {
            return null;
        }
    }

    /**
     * 更新登录成功后更新用户信息
     *
     * @param sysUser
     */
    @Override
    public void updateUserByLogin(SysUser sysUser) {
        if (ObjectUtils.isNotEmpty(sysUser) && ObjectUtils.isNotEmpty(sysUser.getId())) {
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }
    }
    /**
     *
     * 新增用户
     * @param sysUserModel
     * @return
     * @throws CommonException
     */

    /**
     * 修改用户信息
     *
     * @param sysUserModel
     * @return
     */
    @Override
    public CommonResult updateUser(SysUserModel sysUserModel) throws CommonException {
        // 验证参数的规范性
        if (ValidatorUtil.ValidationObject(sysUserModel)) {
            SysUser sysUser = new SysUser();
            // sysUserModel 对象拷贝成 sysuser
            BeanUtils.copy(sysUserModel, sysUser);
            //判断手机号 邮箱是否唯一
            SysUser sysUser1 = checkPhone(sysUser.getPhone());
            if (sysUser1 != null) {
                if (sysUser1.getId() != sysUser.getId()) {
                    return CommonResult.error("手机号已存在！");
                }
            }
            SysUser sysUser2 = checkMail(sysUser.getEmail());
            if (sysUser2 != null) {
                if (sysUser2.getId() != sysUser.getId()) {
                    return CommonResult.error("邮箱已存在！");
                }
            }
            int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
            if (i > 0) {
                return CommonResult.ok(EmErrorCode.UPDATE_OK);
            } else {
                return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
            }
        } else {
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @Override
    public CommonResult delUserById(Integer id) throws CommonException {
        // 判断是否id为空
        if (ObjectUtils.isNotEmpty(id)) {
            int i = sysUserMapper.deleteByPrimaryKey(id);
            // 判断是否操作成功
            if (i > 0) {
                return CommonResult.ok(EmErrorCode.DELETE_OK);
            } else {
                return CommonResult.ok(EmErrorCode.DELETE_ERROR);
            }
        } else {
            throw new CommonException(EmErrorCode.ID_NULL);
        }
    }

    /**
     * 分页查询
     *
     * @param sysUserModel
     * @param pageRequest
     * @return
     */
    @Override
    public CommonResult getUserByPage(SysUserModel sysUserModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        Example example = new Example(SysUser.class);
        // 设置模糊查询
        if (ObjectUtils.isNotEmpty(sysUserModel.getUserName())) {
            example.createCriteria().andLike("userName", "%" + sysUserModel.getUserName() + "%");
        }
        example.orderBy("createTime").desc(); // 添加倒序排序条件
        PageResult pageResult = MybatisPageHelper.getPageResult(sysUserMapper.selectByExample(example));
        return CommonResult.ok(pageResult);
    }

    /**
     * 根据手机号查询用户信息
     *
     * @param phoneAccount
     * @return
     */
    @Override
    public SysUser getUserByPhoneAccount(String phoneAccount) {
        // 判断用户登录名是否为空
        if (ObjectUtils.isNotEmpty(phoneAccount)) {
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("phone", phoneAccount);
            return sysUserMapper.selectOneByExample(example);
        } else {
            return null;
        }
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//        String encode = bCryptPasswordEncoder.encode(String.valueOf(123456));
//        System.out.println(encode);
//        boolean flag = bCryptPasswordEncoder.matches(encode,
//                String.valueOf(123456));
//        if(flag){
//            System.out.println(true);
//        }
        String password = "123456";
//        加密
        String encode = bCryptPasswordEncoder.encode(password);
        System.out.println(encode);
//        解密
        boolean matches = bCryptPasswordEncoder.matches(password, "$2a$10$.9pS3A/oA2pWqyJCBwOHiu2422XKen0x1yUgceElq8k.k0qz38QiC");
        System.out.println(matches);
    }


    /**
     * @description: 查询用户权限
     * @author: dongdong
     * @date: 2023/4/7 17:17
     * @param: [userId]
     * @return: com.zhuiYun.project.common.response.CommonResult
     **/
    @Override
    public CommonResult getUserPower(Integer userId) {
        return CommonResult.ok(sysUserMapper.getUserPower(userId));
    }

    /**
     * 新增用户
     *
     * @param sysUserModel
     * @return
     * @throws CommonException
     */
    @Override
    public CommonResult saveUser(SysUserModel sysUserModel, MultipartFile avatar) throws CommonException {
        // 验证参数的规范性
        if (ValidatorUtil.ValidationObject(sysUserModel)) {

            if (avatar != null) {
                String s = UploadFileUtils.uploadAvatar(avatar);
                log.info("员工添加-图片id-" + s);
                sysUserModel.setAvatarId(Integer.parseInt(s));
            }
            sysUserModel.setUserFlag(0);
            SysUser sysUser = new SysUser();
            // sysUserModel 对象拷贝成 sysuser
            BeanUtils.copy(sysUserModel, sysUser);
            // 设置密码
            sysUser.setUpdateTime(new Date());
            sysUser.setCreateTime(new Date());
            sysUser.setPassword(bCryptPasswordEncoder.encode("123456"));
            int i = sysUserMapper.insertSelective(sysUser);
            if (i > 0) {
                return CommonResult.ok(EmErrorCode.SAVE_OK);
            } else {
                return CommonResult.ok(EmErrorCode.SAVE_ERROR);
            }
        } else {
            return CommonResult.ok(EmErrorCode.SAVE_ERROR);
        }
    }


    @Override
    public CommonResult userPower(Integer userId, List<Integer> integers) {
        int i = sysUserMapper.delPower(userId);
        //获取当前时间
        if (integers.size() > 0) {
            sysUserMapper.userPower(userId, integers);
        }
        return CommonResult.ok();
    }


    @Override
    public CommonResult getPowerByUser() {
        SysUser user = (SysUser) UserUtils.getUser();
        Map<String, Power> map = sysUserMapper.getPowerByUser(user.getId());
        return CommonResult.ok(map);
    }


    /**
     * 分页查询
     *
     * @param sysUserModel
     * @param pageRequest
     * @return
     */
    @Override
    public CommonResult getUserRetrieveByPage(SysUserModel sysUserModel, PageRequest pageRequest) {
        // 设置分页
        MybatisPageHelper.startPage(pageRequest);
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userFlag", 2);
        // 设置模糊查询
        if (ObjectUtils.isNotEmpty(sysUserModel.getUserName())) {
            criteria.andLike("userName", "%" + sysUserModel.getUserName() + "%");
        }
        PageResult pageResult = MybatisPageHelper.getPageResult(sysUserMapper.selectByExample(example));
        return CommonResult.ok(pageResult);
    }


    /**
     * @param id
     * @Author kdj
     * @Description 根据id查询用户
     * @Date 2023/6/13 20:30
     * @Return com.zhuiyun.project.api.sysuser.entiy.SysUser
     */
    @Override
    public SysUser getSysUserById(Integer id) {
        // 判断用户登录名是否为空
        if (ObjectUtils.isNotEmpty(id)) {
            // 使用Example表达式查询登录人信息
            Example example = new Example(SysUser.class);
            example.createCriteria().andEqualTo("id", id);
            return sysUserMapper.selectOneByExample(example);
        } else {
            return null;
        }
    }

    /**
     * @param file
     * @param sysUserModel
     * @Author kdj
     * @Description 修改用户头像
     * @Date 2023/6/13 17:21
     * @Return java.lang.Integer
     */
    @Override
    @Transactional
    public CommonResult updateUserFile(HttpServletRequest request, MultipartFile file, SysUserModel sysUserModel) throws CommonException {
        //判断图片文件是否为空
        if (file != null) {
            String s = UploadFileUtils.uploadAvatar(file);
            if (!ObjectUtils.isNotEmpty(s)) {
                return CommonResult.error(EmErrorCode.UPDATE_ERROR);
            }
            sysUserModel.setAvatarId(Integer.parseInt(s));
        }
        SysUser sysUser = new SysUser();
        // sysUserModel 对象拷贝成 sysuser
        BeanUtils.copy(sysUserModel, sysUser);
        Integer id = sysUser.getId();
        int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        sysUser = getSysUserById(sysUser.getId());
        if (i > 0) {
            //redis
            String token = JWTUtils.createAccessToken(sysUser);
            // 设置token过期时间
            RedisUtil.set(token, sysUser, JWTConfig.expiration);
            RedisUtil.set(sysUser.getLoginName(), token, JWTConfig.expiration);
            token = JWTConfig.tokenPrefix + token;
            //session
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("avatarUrl", sysUser.getAvatarId());
            hashMap.put("token", token);
            UsernamePasswordCodeAuthenticationToken authentication = new UsernamePasswordCodeAuthenticationToken(sysUser);
            // 将user对象交给SecurityContextHolder管理
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return CommonResult.ok(hashMap);
        } else {
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
    }

    /**
     * @param mail
     * @Author kdj
     * @Description pc端邮箱是否存在
     * @Date 2023/6/14 9:32
     * @Return com.zhuiyun.project.api.sysuser.entiy.SysUser
     */
    public SysUser checkMail(String mail) {
        SysUser user = new SysUser();
        user.setEmail(mail);
        //查询验证邮箱是否存在
        return sysUserMapper.selectOne(user);
    }

    /**
     * @param phone
     * @Author kdj
     * @Description pc端手机号是否存在
     * @Date 2023/6/14 9:32
     * @Return com.zhuiyun.project.api.sysuser.entiy.SysUser
     */
    public SysUser checkPhone(String phone) {
        SysUser user = new SysUser();
        user.setPhone(phone);
        //查询验证手机号是否存在
        return sysUserMapper.selectOne(user);
    }

    /**
     * @param sysUserModel
     * @Author kdj
     * @Description 修改用户密码
     * @Date 2023/6/14 10:17
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult updatePassword(SysUserModel sysUserModel) {

        //判断俩次密码是否一致
        String newPassword = sysUserModel.getNewPassword();
        String checkPass = sysUserModel.getCheckPass();
        if (!newPassword.equals(checkPass)) {
            return CommonResult.error("两次密码不一致!");
        }

        //修改密码
        //密码加密
        String encode = bCryptPasswordEncoder.encode(newPassword);
        SysUser sysUser = new SysUser();
        BeanUtils.copy(sysUserModel, sysUser);
        sysUser.setPassword(encode);
        //修改
        int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        if (i > 0) {
            return CommonResult.ok();
        } else {
            return CommonResult.error("修改失败！");
        }

    }

    /**
     * @param id
     * @param password
     * @Author kdj
     * @Description 判断密码是否一致
     * @Date 2023/6/14 10:56
     * @Return com.zhuiyun.project.common.response.CommonResult
     */
    @Override
    public CommonResult checkOldPassword(Integer id, String password) {
        //验证旧密码是否一致
        //用过id查询
        SysUser user = sysUserMapper.selectByPrimaryKey(id);
        boolean matches = bCryptPasswordEncoder.matches(password, user.getPassword());
        if (!matches) {
            return CommonResult.error("密码输入错误！");
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult updateUserByPc(SysUserModel sysUserModel, MultipartFile avatar)  {
        // 验证参数的规范性
//        if (ValidatorUtil.ValidationObject(sysUserModel)) {


        SysUser sysUser = new SysUser();
        // sysUserModel 对象拷贝成 sysUser

        BeanUtils.copy(sysUserModel, sysUser);
        if (avatar != null) {
            String s = UploadFileUtils.uploadAvatar(avatar);
            sysUser.setAvatarId(Integer.valueOf(s));
        }
        //判断手机号 邮箱是否唯一
//            SysUser sysUser1 = checkPhone(sysUser.getPhone());
//            if (sysUser1!= null) {
//                if (sysUser1.getId()!=sysUser.getId()) {
//                    return CommonResult.error("手机号已存在！");
//                }
//            }
//            SysUser sysUser2 = checkMail(sysUser.getEmail());
//            if (sysUser2!= null) {
//                if (sysUser2.getId()!=sysUser.getId()) {
//                    return CommonResult.error("邮箱已存在！");
//                }
//            }

        int i = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        if (i > 0) {
            return CommonResult.ok(EmErrorCode.UPDATE_OK);
        } else {
            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
        }
//        } else {
//            return CommonResult.ok(EmErrorCode.UPDATE_ERROR);
//        }
    }
}
